﻿using System;
using Styx.CommonBot;
using Styx.CommonBot.Routines;

namespace TheFinalCall
{
    public enum TheFinalCallBotEvent
    {
        BotChanged,
        BotStart,
        BotStarted,
        BotStop,
        BotStopped
    }

    public class TheFinalCallBotEventArg : EventArgs
    {
        public readonly TheFinalCallBotEvent Event;

        public TheFinalCallBotEventArg(TheFinalCallBotEvent ev)
        {
            Event = ev;
        }
    }

    partial class TheFinalCallRoutine
    {
        private static bool _botEventSubscribed;

        /// <summary>
        ///     Added to encapsulate any context validation (like are we current routine)
        ///     .. at pont of raising event rather than by every subscriber
        /// </summary>
        public static event EventHandler<TheFinalCallBotEventArg> OnBotEvent;

        private void TheFinalCallBotEventInitialize()
        {
            if (!_botEventSubscribed)
            {
                _botEventSubscribed = true;
                BotEvents.OnBotChanged += e => TheFinalCallRaiseBotEvent(TheFinalCallBotEvent.BotChanged);
                BotEvents.OnBotStart += e => TheFinalCallRaiseBotEvent(TheFinalCallBotEvent.BotStart);
                BotEvents.OnBotStarted += e => TheFinalCallRaiseBotEvent(TheFinalCallBotEvent.BotStarted);
                BotEvents.OnBotStop += e => TheFinalCallRaiseBotEvent(TheFinalCallBotEvent.BotStop);
                BotEvents.OnBotStopped += e => TheFinalCallRaiseBotEvent(TheFinalCallBotEvent.BotStopped);
            }
        }

        public void TheFinalCallRaiseBotEvent(TheFinalCallBotEvent ev)
        {
            try
            {
                if (_botEventSubscribed && RoutineManager.Current.Name == Name)
                    OnBotEvent(this, new TheFinalCallBotEventArg(ev));
            }
            catch
            {
            }
        }
    }
}